<template>
  <div style="width:90%;">
    <el-button @click="goback()" size="mini" type="primary" style="margin-left:800px">返回</el-button>
    <el-form :model="couponForm" :rules="rules" ref="couponForm" label-width="150px">
      <el-input v-model="couponForm.uuid" type="hidden"></el-input>
      <el-input v-model="couponForm.couponType" type="hidden" value="1"></el-input>
      <el-form-item label="优惠券编号：" prop="couponSeq">
        <el-input
          v-model="couponForm.couponSeq"
          :disabled="true"
          style="width:360px;"
          placeholder="保存后自动生成编号"></el-input>
      </el-form-item>
      <el-form-item label="优惠券名称：" prop="couponName">
        <el-input
          v-model="couponForm.couponName"
          :disabled="disabledFlag"
          style="width:360px;"
          placeholder="请输入优惠券名称"
          maxlength="30"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="使用说明：" prop="comments">
        <el-input
          type="textarea"
          v-model="couponForm.comments"
          :disabled="disabledFlag"
          placeholder="请输入卡券使用说明"
          maxlength="100"
          show-word-limit
          :autosize="{minRows:2}"
          style="width:650px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="背景图片：" prop="couponPicture">
        <el-radio-group v-model="couponForm.couponPicture" :disabled="disabledFlag">
          <el-radio-button label="3">
            <img src="../../assets/images/coupon/couponBg3.png" style="width:80px;padding:0px;" />
          </el-radio-button>
          <el-radio-button label="2">
            <img src="../../assets/images/coupon/couponBg2.png" style="width:80px;" />
          </el-radio-button>
          <el-radio-button label="1">
            <img src="../../assets/images/coupon/couponBg1.png" style="width:80px;" />
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="卡券使用条件：" prop="conponLimitMoney">
        <el-input
          v-model="couponForm.conponLimitMoney"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="numberBlur($event,'卡券使用条件')"
          placeholder="请输入使用卡券的最低金额"
        ></el-input>
      </el-form-item>
      <el-form-item label="卡券面值：" prop="couponMoney">
        <el-input
          v-model="couponForm.couponMoney"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="numberBlur($event,'卡券面值')"
          placeholder="请输入卡券的面值"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否启用：">
        <el-radio-group v-model="couponForm.status" :disabled="disabledFlag">
          <el-radio-button label="1">是</el-radio-button>
          <el-radio-button label="0">否</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <!--
      <el-form-item label="商品范围：">
        <el-radio-group v-model="couponForm.useScope" :disabled="disabledFlag">
          <el-radio-button label="0">通用</el-radio-button>
          <el-radio-button label="1">指定商品</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="适用商品：" prop="useScopeList" v-if="couponForm.useScope == '1'">
        <el-table
          :data="useScopeList"
          @selection-change="couponGoodsChecked"
          border
          v-if="couponForm.useScope == '1'"
          style="font-size: 10px;width:100%;"
          height="300"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" width="200" header-align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品编码" width="180" header-align="center"></el-table-column>
          <el-table-column prop="goodsTypeName" label="商品分类" width="180" header-align="center"></el-table-column>
          <el-table-column prop="salePrice" label="商品价格" header-align="center" align="right"></el-table-column>
          <el-table-column prop="unitName" label="销售单位" header-align="center"></el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectGoods()" v-if="!disabledFlag">选择商品</el-button>
          <el-button @click="deleteGoods('couponForm')" v-if="!disabledFlag">删除商品</el-button>
        </div>
      </el-form-item>
      -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('couponForm')" v-if="!disabledFlag">保 存</el-button>
        <el-button @click="resetForm('couponForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择商品" :visible.sync="dialogVisibleGood" width="65%">
      <el-form
        :inline="true"
        :model="formInline"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        商品名称/编码：
        <el-input v-model="formInline.goodsName" style="width:200px;" placeholder="商品名称/编码"></el-input>&nbsp;&nbsp;
        商品分类：
        <el-select v-model="formInline.goodsType">
          <el-option value>全部</el-option>
          <el-option
            v-for="item in goodsTypeList"
            :key="item.goodsTypeId"
            :label="item.goodsTypeName"
            :value="item.goodsTypeId"
          ></el-option>
        </el-select>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getGoodsList()">查询</el-button>
      </el-form>
      <el-table
        :data="goodsList"
        @selection-change="goodsChecked"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" width="200" header-align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品编码" width="180" header-align="center"></el-table-column>
        <el-table-column prop="goodsTypeName" label="商品分类" width="180" header-align="center"></el-table-column>
        <el-table-column prop="salePrice" label="商品价格" header-align="center" align="right"></el-table-column>
        <el-table-column prop="unitName" label="销售单位" header-align="center"></el-table-column>
      </el-table>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleGood = false">取 消</el-button>
        <el-button type="primary" @click="selectConfirm()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {
  queryCouponById,
  createCoupon,
  updateCoupon
} from "@/api/promotionProgramEdit";

import { getGoodsTypeList, querygoodsByName } from "@/api/product";

export default {
  data() {
    return {
      loading: true,
      goodsTypeList: [],
      useScopeList: [],
      goodsList: [],
      lsCouponGoodsList: [],
      lsGoodsList: [],
      couponForm: {
        uuid: "",
        couponSeq: "",
        couponName: "",
        couponType: "1",
        validCreateDate: "",
        validEndDate: "",
        conponLimitMoney: "",
        couponMoney: "",
        useScope: "",
        comments: "",
        status: "",
        couponPicture: "",
        goods: []
      },
      formInline: {
        goodsName: "",
        goodsType: ""
      },
      dialogVisibleGood: false,
      disabledFlag: false,
      listQuery: {
        current: 1,
        size: 10
      },
      total: 0,
      rules: {
        // couponName: [{ required: true, message: "请输入卡券名称", trigger: "blur" }]
      }
    };
  },
  mounted() {
    var v = this.$route.params.edit;
    this.disabledFlag = this.$route.params.disabledFlag;
    if (v) {
      // 修改，回显值
      this.couponForm.uuid = v.uuid;
      this.couponForm.couponSeq = v.couponSeq;
      this.couponForm.couponName = v.couponName;
      this.couponForm.validCreateDate = v.validCreateDate;
      this.couponForm.validEndDate = v.validEndDate;
      this.couponForm.conponLimitMoney = v.conponLimitMoney;
      this.couponForm.couponMoney = v.couponMoney;
      this.couponForm.useScope = v.useScope;
      this.couponForm.comments = v.comments;
      this.couponForm.status = v.status;
      this.couponForm.couponPicture = v.couponPicture;

      this.getCouponById(v.uuid);

      if (!this.disabledFlag && v.used == '1') {
        this.disabledFlag = true;
      }
    } else {
      // 新增，默认值
      this.couponForm.uuid = "";
      this.couponForm.useScope = "0";
      this.couponForm.status = "1";
      this.couponForm.couponPicture = "3";
      this.getGoodsTypeList();
      this.getGoodsList();
    }
  },
  methods: {
    goback() {
      this.$router.go("-1");
    },
    numberBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    discountBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let zz = new RegExp("^[0]+(.[0-9]{1,2})?$");
      if (
        !zz.test(e.target.value) ||
        e.target.value <= 0 ||
        e.target.value >= 1
      ) {
        this.$message({
          message: name + "请输入0-1以内的小数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    getCouponById(uuid) {
      queryCouponById(uuid).then(res => {
        if (
          res.result.memberGoodsInfoDTOS != null &&
          res.result.memberGoodsInfoDTOS.length > 0
        ) {
          this.useScopeList = res.result.memberGoodsInfoDTOS;
        }
        this.getGoodsTypeList();
        this.getGoodsList();
      });
      this.loading = false;
    },
    getGoodsTypeList() {
      getGoodsTypeList().then(res => {
        this.goodsTypeList = res.records;
      });
      this.loading = false;
    },
    getGoodsList() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          goodsName: this.formInline.goodsName,
          goodsTypeId: this.formInline.goodsType
        },
        ascs: [],
        descs: []
      };
      querygoodsByName(data).then(res => {
        this.goodsList = res.records;
        this.total = res.total;
        // 去掉已选的
        for (var i in this.useScopeList) {
          this.removeByValue(this.goodsList, "uuid", this.useScopeList[i].uuid);
          this.total -= 1;
          this.total = this.total < 0 ? 0 : this.total;
        }
      });
      this.loading = false;
    },
    couponGoodsChecked(row) {
      this.lsCouponGoodsList = row;
    },
    goodsChecked(row) {
      this.lsGoodsList = row;
    },
    selectConfirm() {
      // 保存已选择的商品
      this.dialogVisibleGood = !this.dialogVisibleGood;
      this.useScopeList = this.useScopeList.concat(this.lsGoodsList);
      for (var i in this.lsGoodsList) {
        this.removeByValue(this.goodsList, "uuid", this.lsGoodsList[i].uuid);
      }
    },
    selectGoods() {
      // 显示选择商品对话框
      this.dialogVisibleGood = !this.dialogVisibleGood;
    },
    deleteGoods() {
      // 删除已选择的商品
      this.goodsList = this.goodsList.concat(this.lsCouponGoodsList);
      for (var i in this.lsCouponGoodsList) {
        this.removeByValue(
          this.useScopeList,
          "uuid",
          this.lsCouponGoodsList[i].uuid
        );
      }
    },

    submitForm(formName) {
      if (
        this.couponForm.couponName == "" ||
        this.couponForm.couponName == null
      ) {
        this.$message.error("请输入卡券名称");
        return;
      }
      if (
        this.couponForm.conponLimitMoney == "" ||
        this.couponForm.conponLimitMoney == null
      ) {
        this.$message.error("请输入卡券使用条件");
        return;
      }
      if (
        this.couponForm.couponMoney == "" ||
        this.couponForm.couponMoney == null
      ) {
        this.$message.error("请输入卡券面值");
        return;
      }
      if (parseInt(this.couponForm.conponLimitMoney) <= parseInt(this.couponForm.couponMoney)) {
        this.$message.error("卡券使用条件需大于卡券面值，请重新输入");
        return;
      }
      /*
      if (
        this.couponForm.useScope == "1" &&
        (this.useScopeList == null || this.useScopeList.length == 0)
      ) {
        this.$message.error("请选择商品");
        return;
      }
      for (var i in this.useScopeList) {
        this.useScopeList[i].goodsId = this.useScopeList[i].uuid;
        delete this.useScopeList[i].createTime;
        delete this.useScopeList[i].updateTime;
      }
      this.couponForm.goods = this.useScopeList;
      */
      // console.log("this.couponForm");
      // console.log(this.couponForm);
      // return;
      this.$confirm("保存之前请确认所有配置信息是否正确", "提示", {
        confirmButtonText: "保存",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (this.couponForm.uuid == "") {
          // 新增卡券
          createCoupon(this.couponForm).then(res => {
            if (res.code == "1") {
              this.$message({
                showClose: true,
                message: "保存成功",
                type: "success"
              });
              this.$router.push("couponList_ty");
            } else {
              this.$message.error("保存失败");
            }
          });
        } else {
          // 修改卡券
          updateCoupon(this.couponForm).then(res => {
            if (res.code == "1") {
              this.$message({
                showClose: true,
                message: "保存成功",
                type: "success"
              });
              this.$router.push("couponList_ty");
            } else {
              this.$message({
                showClose: true,
                message: "保存失败",
                type: "success"
              });
            }
          });
        }
      }).catch(() => {});
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.$router.push("couponList_ty");
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getGoodsList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getGoodsList();
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    }
  }
};
</script>>
<style lang="less" scoped>
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}
.el-input {
  width: 60%;
}
.search-form-inline {
  border: 1px solid #ebeef5;
  line-height: 30px;
  padding: 12px;
  margin-bottom: 5px;
}
</style>